package library.net.retrofit.request;

import java.io.IOException;
import java.lang.ref.SoftReference;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import library.net.retrofit.RxSchedulers;
import library.net.retrofit.callback.IRxCallback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 自定义进度的RequestBody; 用于文件上传
 *
 * @author Created by WZG on 2016/10/20.
 * @version 1.0
 */
public class RxProgressRequestBody extends RequestBody {
    /**
     * real request body
     */
    private final RequestBody requestBody;
    /**
     * call back interface
     */
    private SoftReference<IRxCallback> mObserverListener;
    /**
     * BufferedSink
     */
    private BufferedSink bufferedSink;

    public RxProgressRequestBody(RequestBody requestBody, IRxCallback progressListener) {
        this.requestBody = requestBody;
        this.mObserverListener = new SoftReference<>(progressListener);
    }

    /**
     * 重写调用实际的响应体的contentType
     *
     * @return MediaType
     */
    @Override
    public MediaType contentType() {
        return null == requestBody ? null : requestBody.contentType();
    }

    /**
     * 重写调用实际的响应体的contentLength
     *
     * @return contentLength
     * @throws IOException 异常
     */
    @Override
    public long contentLength() throws IOException {
        return null == requestBody ? 0 : requestBody.contentLength();
    }

    private long previousTime;

    /**
     * 重写进行写入
     *
     * @param sink BufferedSink
     * @throws IOException 异常
     */
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        previousTime = System.currentTimeMillis();
        if (null == bufferedSink) {
            bufferedSink = Okio.buffer(sink(sink));
        }
        if (null != requestBody)
            requestBody.writeTo(bufferedSink);
        /* 必须调用flush，否则最后一部分数据可能不会被写入 */
        bufferedSink.flush();
    }

    /**
     * 写入，回调进度接口
     *
     * @param sink Sink
     * @return Sink
     */
    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            RequestBodyCount bodyCount = new RequestBodyCount();

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                /* 累加当前写入的字节数 */
                bodyCount.writtenBytesCount += byteCount;
                /* 获得contentLength的值，后续不再调用 */
                if (bodyCount.totalBytesCount == 0) {
                    bodyCount.totalBytesCount = contentLength();
                }
                long totalTime = (System.currentTimeMillis() - previousTime) / 1000;
                if (totalTime == 0) {
                    totalTime += 1;
                }
                bodyCount.networkSpeed = bodyCount.writtenBytesCount / totalTime;
                Observable.just(bodyCount)
                        .compose(RxSchedulers.<RequestBodyCount>io_main())
                        .subscribe(new Observer<RequestBodyCount>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(RequestBodyCount requestBodyCount) {
                                if (mObserverListener.get() != null) {
                                    mObserverListener.get().onProgress(null, requestBodyCount.networkSpeed, requestBodyCount.writtenBytesCount, requestBodyCount.totalBytesCount);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });
            }
        };
    }

    /**
     * current size of RequestBody
     */
    private class RequestBodyCount {
        /* 当前写入字节数 */
        long writtenBytesCount = 0L;
        /* 总字节长度，避免多次调用contentLength()方法 */
        long totalBytesCount = 0L;
        /* 计算网络传输速度（byte/秒） */
        long networkSpeed = 0L;
    }
}